/**
 * 
 */
package org.youisoft.summer.evaluator.function.ext;
import org.youisoft.summer.evaluator.context.CalContext;
import org.youisoft.summer.evaluator.function.AbstractFunction;
import org.youisoft.summer.evaluator.operator.Operator;
import org.youisoft.summer.evaluator.operator.base.ListOperator;
import org.youisoft.summer.evaluator.operator.base.NumberOperator;

/**
 * @author zijiang.jl
 *
 */
public class AverageFunction extends AbstractFunction{


	private static final java.util.List<Class<?>> supports;
	static{
		supports=new java.util.ArrayList<Class<?>>();
		supports.add(ListOperator.class);
		supports.add(NumberOperator.class);
	}

	@Override
	public String getName() {
		return "average";
	}


	

	@Override
	protected boolean checkOperator(int index, Operator<?> operator) {
		return supports.contains(operator.getClass());
	}




	@Override
	public <C,R,P> Operator<?> doInvoke(CalContext<C,R,P> context,Operator<?>... operator) {
		
		if(operator[0] instanceof NumberOperator) return operator[0];
		
		if(operator[0] instanceof ListOperator<?>){
			ListOperator<?> dlo=ListOperator.class.cast(operator[0]);
			NumberOperator no=null;
			for(int i=0;i<dlo.size();i++){
				if(dlo.getOperator(i) instanceof NumberOperator){
					if(no==null) no=NumberOperator.class.cast(dlo.getOperator(0));
					if(i>0) {
						no.add(NumberOperator.class.cast(dlo.getOperator(i)));
					}
				}	
			}
			
			if(no!=null){
				return no.div(new NumberOperator(dlo.size()));

			}	
		}
		return Operator.nullInstance;
	}
	
	@Override
	protected int minOperatorCount() {
		return 1;
	}
}
